package design.patterns.behavioral;


/**
 * 迭代器模式
 * 解释：迭代器模式是一种行为设计模式，
 * 让你能在不暴露集合底层表现形式 （列表、 栈和树等） 的情况下遍历集合中所有的元素。
 */

import lombok.Data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 迭代数字，数字存储在ArrayList 和列表中
 */
public class C_Iterator {

    public static void main(String[] args) {

        LinkedList<String> stringLinkedList = new LinkedList<>();

        ArrayList<String> stringArrayList = new ArrayList<>();

        stringLinkedList.add("1");
        stringLinkedList.add("2");
        stringLinkedList.add("3");
        stringLinkedList.add("4");

        Iterator<String> iterator = stringLinkedList.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        stringArrayList.add("5");
        stringArrayList.add("6");
        stringArrayList.add("7");
        stringArrayList.add("8");

        Iterator<String> iterator1 = stringArrayList.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }

        Friend o1 = new Friend("o1");
        Friend o2 = new Friend("o2");
        Friend o3 = new Friend("o3");
        Friend o4 = new Friend("o4");

        ArrayList<Friend> friends = new ArrayList<>();
        friends.add(o1);
        friends.add(o2);
        friends.add(o3);
        friends.add(o4);

        FriendsIterator friendsIterator = new FriendsIterator(friends);
        while (friendsIterator.hasNext()){
            System.out.println(friendsIterator.next());
        }
    }
}

class Friend{
    private String name;

    public Friend(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Friend{" +
                "name='" + name + '\'' +
                '}';
    }
}
class FriendsIterator implements Iterator<Friend> {
    List<Friend> friendsList = new ArrayList<>();
    private int currentPosition = 0;

    public FriendsIterator(List<Friend> friendsList) {
        this.friendsList = friendsList;
    }

    @Override
    public boolean hasNext() {
        return currentPosition < friendsList.size();
    }

    @Override
    public Friend next() {
        if (!hasNext()){
            return null;
        }
        return friendsList.get(currentPosition++);
    }
}